package com.dmitriyp.movie;

import java.util.ArrayList;
import java.util.List;

import com.dmitriyp.movie.mapping.Movie;

public class EntityObserver {

	private static final EntityObserver INSTANCE = new EntityObserver();

	public static EntityObserver getInstance() {
		return INSTANCE;
	}
	private List<MovieChangeListener> listeners = new ArrayList<MovieChangeListener>();
	
	private EntityObserver() {
		
	}
	
	public void addListener(MovieChangeListener listener) {
		listeners.add(listener);
	}
	
	public void fireEvent(ChangeEvent event) {
		switch (event.getType()) {
		case ADD:
			notifyAdd(event.getMovie());
			break;
		case DELETE:
			notifyDelete(event.getMovie());
			break;
		case UPDATE:
			notifyUpdate(event.getMovie());
			break;
		}
	}
	
	private void notifyAdd(Movie movie) {
		for(MovieChangeListener listener : listeners) {
			listener.add(movie);
		}
	}
	private void notifyUpdate(Movie movie) {
		for(MovieChangeListener listener : listeners) {
			listener.update(movie);
		}
	}
	private void notifyDelete(Movie movie) {
		for(MovieChangeListener listener : listeners) {
			listener.delete(movie);
		}
	}
	
	public static interface MovieChangeListener {
		
		void add(Movie movie);
		
		void update(Movie movie);
		
		void delete(Movie movie);
	}

	public static enum ActionType {
		ADD, DELETE, UPDATE;
	}
}
